#include "logonwindow.h"
#include "ui_logonwindow.h"
#include "signup.h"
#include "tomatoclock.h"
#include "databasemanager.h"
#include <QMessageBox>

logonwindow::logonwindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::logonwindow)
    ,logoned(false)
{
    ui->setupUi(this);
    setWindowTitle("登录");
    setAttribute(Qt::WA_TranslucentBackground, false);
    ui->lineEdit->setStyleSheet("background-color: rgba(28, 28, 28, 28);");
    ui->lineEdit_2->setStyleSheet("background-color: rgba(28, 28, 28, 28);");
    ui->pushButton->setStyleSheet("background-color: rgba(28, 28, 28, 28);");
    ui->pushButton_2->setStyleSheet("background-color: rgba(28, 28, 28, 28);");
}

logonwindow::~logonwindow()
{
    delete ui;
}

void logonwindow::on_pushButton_2_clicked()
{
    int UID = ui->lineEdit->text().toInt();
    QString password = ui->lineEdit_2->text();

    QSqlQuery query(DatabaseManager::getDatabase());
    query.prepare("SELECT COUNT(*) FROM user WHERE UID = :uid AND password = :password");
    query.bindValue(":uid", UID);
    query.bindValue(":password", password);

    if (query.exec() && query.first() && query.value(0).toInt() > 0) {
        // 登录成功
        qDebug() << "Login successful!";
        logoned=true;
        DatabaseManager::initUID(UID);
        QMessageBox::information(this, tr("Success"), tr("登录成功！"));
        tomatoclock *tomatoWindow = new tomatoclock();
        tomatoWindow->show();
        // 关闭登录窗口
        this->close();
    }
    else {
        // 登录失败
        qDebug() << "Login failed!";     
        QMessageBox::critical(this, tr("登录失败"), tr("用户名或密码错误"));
    }
}

void logonwindow::on_pushButton_clicked()
{
    signup *sign_up=new signup;
    sign_up->show();
    this->close();
}

